<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>考核管理</a-breadcrumb-item>
      <a-breadcrumb-item>考核申报</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row>
      <a-col :span="18">
        申报时间范围：
        <a-range-picker
          style="width: 330px"
          v-model="creationDateRange"
          :placeholder="['开始日期', '结束日期']"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          :show-time="{ 
            defaultValue: [
              moment('00:00:00', 'HH:mm:ss'),  // 开始时间默认00:00
              moment('23:59:59', 'HH:mm:ss')   // 结束时间默认23:59
            ]
          }"
          format="YYYY-MM-DD HH:mm:ss"
          @change="changeDate"
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="search()"> 查询 </a-button>&emsp;&nbsp;
        <a-button @click="reset">重置</a-button>
      </a-col>
    </a-row>
    <a-spin :spinning="loading">
      <a-row>
        <a-col :span="24">
          <div class="flex-between">
            <a-button
              v-hasPermi="['khsb:report']"
              type="primary"
              @click="handleOperation('Report')"
            >
              申述上报
            </a-button>
          </div>
          <!-- <div class="flex-between">
            <a-tabs v-model="tabsValue" @change="changeTab">
              <a-tab-pane
                v-for="item in menuList"
                :key="item.value"
                :tab="item.label"
              >
              </a-tab-pane>
            </a-tabs>
            
          </div> -->
          <a-table
            :columns="columns"
            :data-source="tableData"
            :scroll="{ x: 1100 }"
            :pagination="false"
          >
            <span slot="xpiId" slot-scope="text, record">
              <a v-if="text.xpiId" @click="showDetail(text.xpiId, record)">{{text.xpiId}}</a>
            </span>
            <span slot="action" slot-scope="text, record">
              <!-- <a>查看</a>&nbsp;
                <a v-hasPermi="['khsb:audit']">审核</a> -->
              <a
                v-hasPermi="['khsb:audit']"
                class="blue"
                @click="handleOperation('edit', text, record)"
                >编辑</a
              >
              <a-divider type="vertical" />
            </span>
            <!-- <span slot="appealStatus" slot-scope="text,record">
                {{ appealStatusList[record.appealStatus] }}
              </span> -->
          </a-table>
          <div class="page_box">
            <a-pagination
              v-model="queryForm.offset"
              :page-size-options="['20', '30', '40', '50']"
              :total="total"
              show-size-changer
              :page-size="queryForm.current"
              @showSizeChange="onShowSizeChange"
              :show-total="(total) => `共 ${total} 条`"
              @change="pageChange"
            ></a-pagination>
          </div>
        </a-col>
      </a-row>
    </a-spin>

    <a-modal
      :title="indexValue == 'Report' ? '新增' : '编辑'"
      :visible="dialogVisible"
      cancel-text="取消"
      ok-text="确认"
      width="70%"
      @cancel="selectedInputItemValueStatus=false,onCancel()"
      @ok="selectedInputItemValueStatus=false,handleSubmit()"
    >
      <a-form
        :model="dataDialogFrom"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <!-- <a-form-item label="申报状态" >
          <a-select  v-model:value="dataDialogFrom.appealStatus" v-decorator="[  'appealStatus',  { rules: [{ required: true, message: '请选择申报状态' }] }, ]" placeholder="请选择申报状态" style="width: 100%"  >
            <a-select-option v-for="(item, index) in appealStatusD"  :key="index"  :value="item.value" >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item> -->
        
        <a-form-item label="申报事件">
           <a-table
            v-if="selectedInputItemValueStatus"
            :scroll="{ x: 500 }"
            :columns="columns3"
            :data-source="selectedInputItemValue2s"
            :pagination="false"
            style="height: 144px; overflow-y: auto"
            rowKey="id"
          ></a-table>
          <a-button type="primary" @click="selectEvent">选择事件</a-button>
        </a-form-item>
        <a-form-item label="申报主体">
          <a-input
            v-model:value="dataDialogFrom.appealBelong"
            v-decorator="[
              'appealBelong',
              { rules: [{ required: true, message: '请输入申报主体' }] },
            ]"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="分数">
          <a-input
            v-model:value="dataDialogFrom.getSocre"
            v-decorator="[
              'getSocre',
              { rules: [{ required: true, message: '请输入加分分数' }] },
            ]"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="分数类型">
          <a-select
            v-model:value="dataDialogFrom.getType"
            v-decorator="[
              'getType',
              { rules: [{ required: true, message: '请选择分数类型' }] },
            ]"
            placeholder="请选择分数类型"
            style="width: 100%"
          >
            <a-select-option
              v-for="(item, index) in getTypeD"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="取得社会影响">
          <a-textarea
            v-model:value="dataDialogFrom.contribute"
            v-decorator="[
              'contribute',
              { rules: [{ required: true, message: '请输入取得社会影响' }] },
            ]"
            :rows="4"
            placeholder="请填写取得社会影响"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>

      <a-modal
        title="选择事件"
        :visible="eventVisible"
        width="80%"
        ok-text="确认"
        cancel-text="取消"
        @cancel="eventVisible = false"
        @ok="putEvent"
      >
        <a-table
          :scroll="{ x: 500 }"
          :columns="columns2"
          :data-source="tableData2"
          :loading="loading2"
          :pagination="false"
          style="height: 400px; overflow-y: auto"
          rowKey="id"
          :rowSelection="{
            type: 'radio',
            onChange: rowSelectedChange2,
          }"
        ></a-table>
        <div style="display: flex; justify-content: center; margin-top: 20px">
          <a-pagination
            v-model="queryForm2.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total2"
            show-size-changer
            :page-size="queryForm2.current"
            @showSizeChange="onShowSizeChange2"
            :show-total="(total) => `共 ${total} 条`"
            @change="pageChange2"
          />
        </div>
      </a-modal>
    </a-modal>

    <!-- ------事件详情 --------- -->
     <a-modal
        title="事件详情"
        :visible="eventVisible2"
        width="80%"
        ok-text="确认"
        cancel-text="取消"
        @cancel="eventVisible2 = false"
        @ok="eventVisible2 = false"
      >
        <a-table
          :scroll="{ x: 500 }"
          :columns="columns2"
          :data-source="tableData3"
          :pagination="false"
          style="height: 400px; overflow-y: auto"
          rowKey="id"
        ></a-table>
      </a-modal>
  </div>
</template>
<script>
import { appealStatusList } from "./common";
import dayjs from "dayjs";
import moment from "moment";
import dictMixin from "@/mixins/dictMixin";

const columns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
    
  },
  {
    title: "申报状态",
    dataIndex: "appealStatus",
    key: "appealStatus",
    
    customRender: (text, record, index) => {
      console.log(text);
      return text == 0
        ? "未审核"
        : text == 1
        ? "已通过"
        : text == 2
        ? "已驳回"
        : "";
    },
  },
  {
    title: "取得社会影响",
    dataIndex: "contribute",
    key: "contribute",
    
  },
  {
    title: "申报类型",
    dataIndex: "appealType",
    key: "appealType",
    
  },
  {
    title: "申报主体",
    dataIndex: "appealBelong",
    key: "appealBelong",
    
  },
  {
    title: "分数",
    dataIndex: "getSocre",
    key: "getSocre",
    
  },
  {
    title: "申报人",
    dataIndex: "pusherUserName",
    key: "pusherUserName",
    
    // customRender: (text, record, index) => {
    //   console.log('texttexttext',text)
    // },
  },
  {
    title: "申报时间",
    dataIndex: "pusherTime",
    key: "pusherTime",
   
  },
  {
    title: "事件id",
    key: "xpiId",
     
    scopedSlots: { customRender: "xpiId" },
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    fixed: "right",
  },
];

export default {
  mixins: [dictMixin],

  data() {
    return {
      tableData: [],
      columns,
      loading: false,
      eventVisible: false,
      eventVisible2: false,
      appealStatusList: appealStatusList,
      queryForm: {
        current: 20,
        offset: 1,
        startTime: "",
        endTime: "",
      },
      total: 0,
      tabsValue: null,
      menuList: [
        { label: "申报列表", value: null },
        // {label: '审核列表', value: 1},
      ],
      creationDateRange: [],
      dialogVisible: false,
      dialogTitle: "",
      dataDialogFrom: {
        appealBelong: "",
        appealStatus: "",
        appealType: "个人",
        contribute: "",
        getSocre: "",
        getType: "",
        pusherTime: "",
        pusherUserId: "",
        xpiId: null,
        id: null,
      },
      appealStatusD: [
        { value: 0, label: "未审核" },
        { value: 1, label: "已通过" },
        { value: 2, label: "已驳回" },
      ],
      getTypeD: [
        { value: 0, label: "减分" },
        { value: 1, label: "加分" },
      ],
      pusherTimeData: [],
      indexValue: "",
      columns2: [
        {
          title: "", // 添加单选列
          dataIndex: "rowKey",
          key: "rowKey", // 自定义列的key，用于在模板中引用
          width: "50px",
        },
        { title: "事件编号", dataIndex: "eventId", key: "eventId" },
        {
          title: "受理状态",
          dataIndex: "businessStatus",
          key: "businessStatus",
          customRender: (text, record, index) => {
            // console.log(text)
            return text == 0
              ? "暂存"
              : text == 1
              ? "已上报"
              : text == 2
              ? "直接办结"
              : "";
          },
        },
        {
          title: "紧急程度",
          dataIndex: "urgencyLevel",
          key: "urgencyLevel",
          customRender: (text, record, index) => {
            // console.log(text)
            return text == 0
              ? "一般"
              : text == 1
              ? "优先"
              : text == 2
              ? "紧急"
              : "";
          },
        },
        {
          title: "办理状态",
          dataIndex: "eventStatus",
          key: "eventStatus",
          customRender: (text, record, index) => {
            // console.log(text)
            return (
              (this.dealStatusList.find((item) => item.value == text) || {})
                .label || ""
            );
          },
        },
        {
          title: "关联对象",
          dataIndex: "relatedObjectName",
          key: "relatedObjectName",
        },
        {
          title: "案件描述",
          dataIndex: "issueDescription",
          key: "issueDescription",
        },
        {
          title: "问题来源",
          dataIndex: "issueSource",
          key: "issueSource",
        },
        {
          title: "问题类型",
          dataIndex: "issueType",
          key: "issueType",
        },
        {
          title: "处理人用户名",
          dataIndex: "reporterName",
          key: "processUserName",
        },
        { title: "上报人姓名", dataIndex: "reporterName", key: "reporterName" },
        {
          title: "上报人电话",
          dataIndex: "reporterPhone",
          key: "reporterPhone",
        },
        { title: "上报时间", dataIndex: "reportTime", key: "reportTime" },
      ],
      columns3: [
        { title: "事件编号", dataIndex: "eventId", key: "eventId" },
        {
          title: "关联对象",
          dataIndex: "relatedObjectName",
          key: "relatedObjectName",
        },
        // {
        //   title: "案件描述",
        //   dataIndex: "issueDescription",
        //   key: "issueDescription",
        // },
        // {
        //   title: "处理人用户名",
        //   dataIndex: "reporterName",
        //   key: "processUserName",
        // },
        // { title: "上报人姓名", dataIndex: "reporterName", key: "reporterName" },
      ],
      tableData2: [],
      tableData3: [],
      queryForm2: { current: 10, offset: 1 },
      total2: 0,
      loading2: false,
      selectedInputItemValue2: {}, // 当前选中的行
      selectedInputItemValue2s:[],
      selectedInputItemValueStatus: false,
      userIdList: [],
    };
  },
  mounted() {
    let userInfo = JSON.parse(localStorage.getItem("userInfo"));

    this.dataDialogFrom.pusherUserId = userInfo.userId;
    this.dataDialogFrom.pusherTime = this.formatTimeDateTime();
    this.getList();
    // this.getPusher();
  },
  methods: {
    moment,
    // 分页
    onShowSizeChange(current, pageSize) {
      this.queryForm.offset = current;
      this.queryForm.current = pageSize;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    changeDate(val) {
      this.queryForm.startTime = val[0];
      this.queryForm.endTime = val[1];
    },
    // async getList() {
    //   this.loading = true
    //   const url1 = '/government-platform-center/socreAppeal?current='+this.queryForm.current+'&offset='+ this.queryForm.offset + '&startTime='+ this.queryForm.startTime +'&endTime=' + this.queryForm.endTime
    //   const url2 = '/government-platform-center/socreAppeal/getSocreAppealListForDept?current='+this.queryForm.current+'&offset='+ this.queryForm.offset + '&startTime='+ this.queryForm.startTime +'&endTime=' + this.queryForm.endTime
    //   this.$axios.get(this.tabsValue == 1 ? url2 : url1).then((res) => {
    //     if (res.data.code == 0) {
    //       this.tableData = res.data.data
    //       this.total = res.data.total
    //       this.loading = false;
    //       this.userIdList = [];
    //       this.tableData.map(v=>{
    //         const userName = await this.getUser(v.pusherUserId); // 要等接口回来才处理

    //         this.userIdList.push({name:userName})
    //       })
    //       console.log(this.userIdList)
    //     }
    //   })
    // },
    async getList() {
      try {
        this.loading = true;

        // 使用模板字符串提高可读性
        const baseUrl =
          this.tabsValue === 1
            ? "/government-platform-center/socreAppeal/getSocreAppealListForDept"
            : "/government-platform-center/socreAppeal";

        const params = {
          current: this.queryForm.current,
          offset: this.queryForm.offset,
          startTime: this.queryForm.startTime,
          endTime: this.queryForm.endTime,
        };

        const res = await this.$axios.get(baseUrl, { params });

        if (res.data.code !== 0) {
          throw new Error("请求失败: " + res.data.message);
        }

        // this.tableData = res.data.data;
        this.total = res.data.total;

        // 使用 Promise.all 并行处理所有用户请求
        this.tableData = await Promise.all(
          res.data.data.map(async (item) => ({
            ...item,
            // 直接添加 pusherUserName 字段到每行数据
            pusherUserName: await this.getUser(item.pusherUserId),
          }))
        );

        // console.log('处理后的用户列表:', this.userIdList);
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("数据加载失败");
      } finally {
        this.loading = false;
      }
    },

    search() {
      this.tableData = [];
      this.queryForm.offset = 1;
      this.getList();
    },
    reset() {
      this.tableData = [];
      this.creationDateRange = [];
      this.queryForm.offset = 1;
      this.queryForm.startTime = "";
      this.queryForm.endTime = "";
      this.getList();
    },
    handleOperation(index, data) {
      if (index == "edit") {
        console.log("编辑", data);
        this.dataDialogFrom = {
          appealBelong: data.appealBelong,
          appealStatus: data.appealStatus,
          appealType: "个人",
          contribute: data.contribute,
          getSocre: data.getSocre,
          getType: data.getType,
          pusherTime: data.pusherTime,
          pusherUserId: data.pusherUserId,
          xpiId: data.xpiId,
          id: data.id,
        };
      }
      this.indexValue = index;
      this.dialogVisible = true;
    },
    changeTab(e) {
      this.tabsValue = e;
      this.queryForm.current = 20;
      this.queryForm.offset = 1;
      console.log("--切换--", this.queryForm.appealStatus);
      this.getList();
    },

    handleSubmit() {
      let url =
        this.indexValue == "Report"
          ? "/government-platform-center/socreAppeal"
          : "/government-platform-center/socreAppeal/edit";
      console.log("-----------", this.dataDialogFrom);
      let parm = {
        appealBelong: this.dataDialogFrom.appealBelong,
        appealStatus: 0, // this.dataDialogFrom.appealStatus,
        appealType: "个人",
        contribute: this.dataDialogFrom.contribute,
        getSocre: this.dataDialogFrom.getSocre,
        getType: this.dataDialogFrom.getType,
        pusherTime: this.dataDialogFrom.pusherTime,
        pusherUserId: this.dataDialogFrom.pusherUserId,
        xpiId: this.dataDialogFrom.xpiId,
      };
      // const url = `/government-platform-center/socreAppeal`
      this.$axios
        .post(url, parm, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((res) => {
          console.log("--", res.data);
          // this.pusherTimeData = res.data.data;
          this.getList();
          this.dialogVisible = false;
        });
    },
    formatTimeDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以要加1
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    onCancel() {
      this.dialogVisible = false;
      let parm = {
        appealBelong: "",
        appealStatus: "",
        appealType: "个人",
        contribute: "",
        getSocre: null,
        getType: null,
        // pusherTime: '',
      };
    },
    // ---------------弹窗
    rowSelectedChange2(_, row) {
      this.selectedInputItemValue2 = row[0];
      this.selectedInputItemValue2s = row;

      // console.log('选择的事件----',this.selectedInputItemValue2)
    },
    changePage2(e) {
      this.queryForm2.offset = e;
      this.selectEvent();
    },
    selectEvent() {
      this.eventVisible = true;
      this.loading2 = true;
      const url = `/government-platform-center/case/getCaseFlow`;
      this.$axios
        .post(
          url,
          { exceFlag: 0,current:this.queryForm2.current,offset:this.queryForm2.offset },
          {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          }
        )
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData2 = res.data.data;
            this.total2 = res.data.total;
          }
        })
        .finally(() => {
          this.loading2 = false;
        });
    },
    //实践操作
    putEvent() {
      (this.dataDialogFrom.xpiId = this.selectedInputItemValue2.eventId),
        console.log(this.selectedInputItemValue2);
        this.selectedInputItemValueStatus = true;
        this.eventVisible = false;
    },
    // 正确返回 Promise 的方法
    getUser(id) {
      return this.$axios
        .get("/government-platform-center/user/getUserInfo?userId=" + id)
        .then((res) => {
          return res.data.data.userName;
        })
        .catch((error) => {
          // 建议添加错误处理
          console.error("获取用户失败:", error);
          return "未知用户"; // 返回默认值
        });
    },

    showDetail(eventId) {
      this.eventVisible2 = true;
      console.log('eventId',eventId)
      const url = `/government-platform-center/case/getCaseFlow`;
      this.$axios.post(url,
          { exceFlag: 0,current: 20,offset:1,eventId:eventId	 },
          {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          }
        )
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData3 = res.data.data;
          }
        })
        .finally(() => {
        });
    },
    onShowSizeChange2(current, pageSize) {
      this.queryForm2.offset = current;
      this.queryForm2.current = pageSize;
      this.selectEvent();
    },
    pageChange2(current) {
      this.queryForm2.offset = current;
      this.selectEvent();
    },
  },
};
</script>
<style scoped>
.ant-row {
  border-radius: 5px;
  margin-bottom: 15px;
  background: #fff;
  padding: 20px;
  color: #000;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/deep/ .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold;
}

/deep/ .ant-table-tbody > tr > td {
  color: #000;
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}
.table {
  width: 100%;
  overflow-x: auto !important;
}

/* 添加表格原生滚动条样式 */
::v-deep .ant-table-body {
  overflow-x: auto !important;
  /* overflow-y: auto !important; */
  /* max-height: 500px; 设置最大高度，超出时显示垂直滚动条 */
}

/* 确保使用原生滚动条样式 */
::v-deep .ant-table-body::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::v-deep .ant-table-body::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

::v-deep .ant-table-body::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

/* 修复固定列的问题 */
::v-deep .ant-table-fixed-right {
  right: 0px; /* 为滚动条留出空间 */
}
</style>
